//
//  HMPullDownRefreshControlHeight.swift
//  WymanWeibo
//
//  Created by wyman on 16/4/16.
//  Copyright © 2016年 wyman. All rights reserved.
//

import UIKit

private let HMPullDownRefreshControlHeight: CGFloat = 60

enum HMPullDownRefreshControlStatus {
    case Normal  //箭头朝下,下拉刷新
    case PushToRefresh //箭头朝上,释放刷新
    case Refreshing //正在刷新
}

//@available(iOS 9.0, *)
class HMPullDownRefreshControlNor: UIView {
    private var superScrollView: UIScrollView?
    
    //定义刷新的闭包
    
    var pullDownRefreshHandler: (() -> ())?
    
    private var currentstatus: HMPullDownRefreshControlStatus = HMPullDownRefreshControlStatus.Normal
        {
        didSet{
        //状态换了,根据不同设置设置不同内同
            switch currentstatus {
            case .Normal:
                HMPrint("Normal")
            //隐藏风火轮
                fhlView.hidden = true
            
                //显示箭头
                arrowView.hidden = false
                
                //箭头回到初始位置
                meesageLabel.text = "下拉刷新"
                
                UIView.animateWithDuration(HMDefautlAnimDuration, animations: { 
                    self.arrowView.transform = CGAffineTransformIdentity
                })
                
            case .PushToRefresh:
                
                meesageLabel.text = "释放刷新"
                UIView.animateWithDuration(HMDefautlAnimDuration, animations: {
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                fhlView.hidden = false
                arrowView.hidden = true
                meesageLabel.text = "正在刷新"
                //设置动画
                
            //添加动画
                let animationAnim = CABasicAnimation(keyPath: "transform.rotation")
                
                animationAnim.repeatCount = MAXFLOAT
                animationAnim.duration = 1
                animationAnim.toValue = M_PI*2
                animationAnim.removedOnCompletion = false
                
                fhlView.layer.addAnimation(animationAnim, forKey: "rotationAnim")
                
                //滚动完了 .调用数据
                UIView.animateWithDuration(HMDefautlAnimDuration, animations: { 
                    self.superScrollView?.contentInset.top += HMPullDownRefreshControlHeight
                })
            
                pullDownRefreshHandler?()
            }
            
        
        }
    }
    //结束刷新
    
    func startRefreshing(){
    currentstatus = .Refreshing
    }
    
    func endRefresh(){
    
        currentstatus = .Normal
        
        UIView.animateWithDuration(HMDefautlAnimDuration) { 
            self.superScrollView?.contentInset.top -= HMPullDownRefreshControlHeight
        }
    
    }
    
    override init(frame: CGRect) {
        let newFrame = CGRect(x: 0, y: -HMPullDownRefreshControlHeight, width: UIScreen.mainScreen().bounds.size.width, height: HMPullDownRefreshControlHeight)
        
        super.init(frame: newFrame)
        
        //准备控件
        prepareUI()
        
        
    }
    
    private func prepareUI(){
        
        fhlView.hidden = true
    addSubview(arrowView)
    addSubview(fhlView)
    addSubview(meesageLabel)
    
        //设置约束
        fhlView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        
        arrowView.snp_makeConstraints { (make) in
            make.center.equalTo(fhlView)
        }
    
        meesageLabel.snp_makeConstraints { (make) in
            make.leading.equalTo(fhlView.snp_trailing).offset(10)
            make.centerY.equalTo(fhlView)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let scrollView = newSuperview as? UIScrollView{
            
            superScrollView = scrollView
        superScrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        
        
        }}
    
    
        
    deinit {
    removeObserver(self, forKeyPath: "contentOffset")
    }
    

    //实现监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {

        
        //在这个方法里面判断,并且调用状态
        if superScrollView!.dragging{
        if  currentstatus == .PushToRefresh && superScrollView?.contentOffset.y > -(superScrollView!.contentInset.top+HMPullDownRefreshControlHeight){
        currentstatus = .Normal
        HMPrint("切换到Normal")
        }else if currentstatus == .Normal && superScrollView?.contentOffset.y < -(superScrollView!.contentInset.top+HMPullDownRefreshControlHeight){
        HMPrint("切换到Pull")
        currentstatus = .PushToRefresh
        }
        }else if currentstatus == .PushToRefresh
        {
        HMPrint("去刷新")
            
            currentstatus = .Refreshing
        
        }
        
        
        
        
    }
    
    //箭头
    private lazy var arrowView: UIImageView = UIImageView.init(image: UIImage(named: "tableview_pull_refresh"))
    
    //风火轮
    private lazy var fhlView: UIImageView = UIImageView.init(image: UIImage(named: "tableview_loading"))
    
    //文字
    private lazy var meesageLabel: UILabel = {
    let label = UILabel(fontSize: 14,textColor: UIColor.darkGrayColor())
        
    label.text = "下拉刷新"
    return label
    }()
    
    

}
